package controller;


import constant.Constants;
import convert.myconvert;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import pojo.User;
import service.UserService;
import service.impl.UserServiceimpl;
import utils.MD5Utils;
import utils.UUIDUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.6 下午 23:37
 *
 * 前台用户模块
 *
 */
@WebServlet("/user")
@SuppressWarnings("all")
public class UserServlet extends BaseServlet {
    /**
     * 注册界面
     * @param request
     * @param response
     * @return
     */
    public String registerUI(HttpServletRequest request, HttpServletResponse response){
        return "/jsp/register.jsp";
    }

    /**
     * 异步校验用户名是否存在
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String CheckUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
        /* response.setContentType("text/html;charset = utf-8");*/
        String username = request.getParameter("name");
        System.out.println("username:"+username);
        UserService userService = new UserServiceimpl();
        boolean flag = userService.getuserByname(username);
        if(flag==true){
            response.getWriter().write("1");
        }else {
            response.getWriter().write("0");
        }
        return null;
    }

    /**
     * 用户注册
     * @param request
     * @param response
     * @return
     */
    public String register(HttpServletRequest request,HttpServletResponse response){
        /*  request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset = utf-8 ");*/

        String code = request.getParameter("code");
        //先处理验证码,验证码存储在服务器端HttpSession

        //获取session
        HttpSession session = request.getSession();
        //从session域获取CHECKCODE_SERVER绑定的内容
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //一次性验证
        session.removeAttribute("CHECKCODE_SERVER");

        if(!code.equalsIgnoreCase(checkcode_server) || code == null){
            request.setAttribute("msg","验证码错误");
            return "/jsp/msg.jsp";
        }

        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        //处理日期
        ConvertUtils.register(new myconvert(), Date.class);
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        user.setUid(UUIDUtils.getId());
        //密码加密
        user.setPassword(MD5Utils.md5(user.getPassword()));
        //激活码
        user.setCode(UUIDUtils.getCode());

        UserService userService = new UserServiceimpl();
        userService.addUserget(user);


        //用户注册成功
        //给request域中添加一个绑定参数数据
        request.setAttribute("msg","恭喜您,用户注册成功,请前往邮箱激活");
        return "/jsp/msg.jsp";

    }

    /**
     * 邮箱激活
     * @param request
     * @param response
     * @return
     */
    public String active(HttpServletRequest request,HttpServletResponse response) {
        String code = request.getParameter("code");
        UserService userService = new UserServiceimpl();
        User user = userService.getCode(code);

        if (user == null) {
            request.setAttribute("msg", "用户激活失败,请重新激活");
        } else {
            //存在
            request.setAttribute("msg", "恭喜您,用户激活成功,请登录</a>");
        }
        return "/jsp/msg.jsp";
    }

    /**
     * 登录界面
     * @param request
     * @param response
     * @return
     */
    public String loginUI(HttpServletRequest request,HttpServletResponse response){
        return "/jsp/login.jsp";
    }

    public  String login(HttpServletRequest request,HttpServletResponse response)
            throws IOException {
/* //处理乱码:post/响应乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");*/

        String logincode = request.getParameter("logincode");

        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        session.removeAttribute("CHECKCODE_SERVER");

        if (!logincode.equalsIgnoreCase(checkcode_server) || logincode == null) {
            request.setAttribute("msg", "验证码错误");
            return "/jsp/login.jsp";
        }

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = new UserServiceimpl();
        User user = userService.UserLogin(username, password);

        //如果当前用户不存在
        if(user==null){
            //错误提示
            request.setAttribute("msg","用户名或者密码错误");
           return "/jsp/login.jsp";
        }

        //如果用户存在
        //还要判断登录的用户状态是否为1,不为1,重新激活
        if(user.getState()!= Constants.USER_ACTIVE_STATE){
            //用户未激活
            request.setAttribute("msg","用户未激活,请先<a href='http://localhost:8080/AdminSystem_war/user?methodName=active&code="+user.getCode()+"'>激活用户</a>");
            return "/jsp/msg.jsp";
        }

        //如果没有问题
        //将user对象存储到session中
        session.setAttribute("user",user);

        //获取前台name="auto_User"参数
        String auto_User = request.getParameter("auto_User");
        //判断用户是否勾选
        if(!"AutoUser".equals(auto_User)){
            //没有勾选
            //创建Cookie
            Cookie cookie = new Cookie("autoUser","") ;
            //有效期:0:表示自动删除cookie
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }else{
            //定义一个内容:将用户名和密码使用":"拼接
            String content = username+":"+password ;
            //加密:jdk提供的加密工具
            content =  URLEncoder.encode(content,"utf-8") ;
            //勾选了
            Cookie cookie = new Cookie("autoUser",content) ;
            //设置有效期:5min
            cookie.setMaxAge(60*5);
            //将cookie信息携带浏览器
            response.addCookie(cookie);

        }
        response.sendRedirect(request.getContextPath()+"/");
        return null;

    }

    /**
     * 登录退出
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    public String logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        //手动删除session,使这个会话无效
        session.invalidate();
        //重定向到首页

        //判断cookie,如果cookie的名称存在"autoUser",清除掉,删除cookie(设置有效期为0)


        response.sendRedirect(request.getContextPath()+"/");
        return null;
    }


}
